package com.turing.post.report.impl;

import java.math.BigInteger;
import java.util.Date;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.report.util.MerchantPastIncomeDetail;
import com.turing.post.report.util.MerchantPastIncomeDetailDao;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;


@Stateless(mappedName = "report.impl.MerchantPastIncomeDetailDaoImpl")
@Remote
@Local
public class MerchantPastIncomeDetailDaoImpl implements
		MerchantPastIncomeDetailDao {

	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;
	
	@Override
	public BigInteger getTotalSIncomeByMerchantNo_Trandate_Salbranchno(
			String merchantNo, Date tranDate,String SaleBranchNo) {
		// TODO Auto-generated method stub
		Query query = _em
		.createNativeQuery("select nvl(sum(SIncomeDiff),0) from MerchantPastIncomeDetail t "
				+ "where t.merchantNo = ?1 and t.tranDate = ?2 and salebranchno=?3");
		query.setParameter(1, merchantNo);
		query.setParameter(2, tranDate);
		query.setParameter(3, SaleBranchNo);
		return new BigInteger(query.getSingleResult().toString());
	}
	
	@Override
	public BigInteger getTotalMIncomeByMerchantNo_Trandate_Salbranchno(
			String merchantNo, Date tranDate,String SaleBranchNo) {
		// TODO Auto-generated method stub
		Query query = _em
		.createNativeQuery("select nvl(sum(MIncomeDiff),0) from MerchantPastIncomeDetail t "
				+ "where t.merchantNo = ?1 and t.tranDate = ?2 and salebranchno=?3");
		query.setParameter(1, merchantNo);
		query.setParameter(2, tranDate);
		query.setParameter(3, SaleBranchNo);
		return new BigInteger(query.getSingleResult().toString());
	}
	
	/**
	 * 根据商户号，时间段，得到某段时间的收入总额
	 * 
	 * @param merchantno
	 * @param startdate
	 * @param enddate
	 * @return
	 */
	@Override
	public Long getAllIncomeByDate(String merchantno, Date startdate,
			Date enddate) {
		String sql = "select nvl(sum(sincome+sincome),0) from MerchantPastIncomeDetail where merchantno=?1 and trandate between ?2 and ?3";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, merchantno);
		query.setParameter(2, startdate);
		query.setParameter(3, enddate);
		return new BigInteger(query.getSingleResult().toString()).longValue();
	}
	
	/**
	 * 新增操作
	 * @param mpid
	 * @throws PCPSApplicationException
	 */
	@Override
	public void insertMerchantPastIncomeDetail(MerchantPastIncomeDetail mpid)	throws PCPSApplicationException
	{
		GeneralDao.insert(_em, mpid);
	}

}
